import React, { useState, useEffect } from 'react'
import { Table, Badge, Input, message, Button, InputNumber, Modal } from 'antd';
import MultipleUser from '../List/components/MultipleUser';
import './editer.css'
import dayjs from 'dayjs';
import { UdDateRangePicker, http, UdPageHeader, UdPage, UdTable, columnRenders, routeUtils } from '@/lib';
import moment from 'moment';
import apis from '@/apis/AboutQuota';
import { EDealerType } from '../../AdjustTheRecord/List';
import _ from 'lodash';
import { EListType, queryUrls } from '../List/config.options';

const { TextArea } = Input;

const dateFormat = 'YYYY-MM-DD';
let setFlowReqVos = []
function NestedTable(props) {
  const [data, setData] = useState([])
  const [inputValue, setInputValue] = useState([''])
  const [titleValue, setTitleValue] = useState('')

  // 
  const [visible, toggleVisible] = useState(false);
  const [confirmLoading, toggleLoading] = useState(false);
  const [extraText, extraTextChange] = useState('');
  const [pagination, setPagination] = useState(false) as any
  const { brandName } = routeUtils.searchStringToObject(props.location.search, { brandCode: '', brandName: '' })

  useEffect(() => {
    if (props.location.state?.brandCode) {
      let { filterValues, brandCode } = props.location.state
      getList(brandCode, filterValues)
    } else {
      let title = brandName + props.match.params.times + '配额下达审批'
      setTitleValue(title)
      handelgetData()
      return componentWillUnmount
    }
  }, [pagination.page, pagination.size])
  function componentWillUnmount() {
    // 组件销毁时执行的代码
    setFlowReqVos = []
    sessionStorage.removeItem('person')
    sessionStorage.removeItem('checkedList')
  }

  function handleChangePage(page, pageSize) {
    let { filterValues, brandCode } = props.location.state;
    filterValues.page = page
    filterValues.pageSize = pageSize
    getList(brandCode, filterValues)
  }

  function getList(brandCode, filterValues) {
    http.post(queryUrls[EListType.CUSTOMER_TYPE], { ...filterValues, brandCode }).then(res => {
      let list = res.data.content;
      if (!list.length) return
      let title = list[0].brandName + dayjs(list[0].inventoryBegineTime).format('YYYY年MM月') + '配额下达审批';
      setTitleValue(title)
      setData(list);
      setPagination({
        total: res.data.totalElements,
        current: res.data.number,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
        onChange: (page, pageSize) => { handleChangePage(page, pageSize) },
        onShowSizeChange: (current, size) => { handleChangePage(current, size) }
      })
    })
  }

  const expandedRowRender = (record, index, indent, expanded) => {
    if (!expanded) {
      return null
    }
    let dataSource = record.quotaModifyHistoryRespVoList
    const columns = [
      { title: '序号', dataIndex: 'id', key: 'id', width: 50, render: (text, reoder, index) => index + 1 },
      { title: '物料分类名称', dataIndex: 'groupName', key: 'groupName', width: 200 },
      {
        title: '当前动销/件',
        key: 'nowMove',
        dataIndex: 'nowMove',
        width: 100,
        render: (text, record) => (
          <span>
            <a onClick={() => this.handelCurrentPin(record)}>{text}</a>
          </span>
        ),
      },
      { title: '理论配额值/件', dataIndex: 'quotaCountNum', key: 'quotaCountNum', width: 140 },
      { title: '片区申请配额/件', dataIndex: 'oldQuotaNum', key: 'oldQuotaNum', width: 140 },
      {
        title: '实际配额', dataIndex: 'quotaNum', key: 'quotaNum', width: 140, render: (text, record) => (
          <>
            {props.location.state?.brandCode ? <span>{text}</span> :
              <InputNumber defaultValue={text} onBlur={(e) => changeData(e.target.value, 'quotaNum', record)} min={0} max={2 ** 31} maxLength={9} style={{ width: 110 }} />
            }
          </>
        )
      },
      {
        title: '配额有效期', dataIndex: 'quotaStartTime', width: 240, render: (text, record) => {
          let render = record.quotaStartTime ? moment(record.quotaStartTime).format('YYYY-MM-DD') : ''
          render += record.quotaEndTime ? '~' + moment(record.quotaEndTime).format('YYYY-MM-DD') : ''
          return render
          /* 配额有效期暂不可编辑 */
          /* const startTime = record.quotaStartTime ? moment(record.quotaStartTime, dateFormat) : undefined
          const endTime = record.quotaEndTime ? moment(record.quotaEndTime, dateFormat) : undefined
          return (
            <UdDateRangePicker 
              defaultValue={[startTime, endTime]}
              valueFormat={['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59']}
              onChange={(dates) => changeData(dates, ['quotaStartTime', 'quotaEndTime'], record)}
            />
          ) */
        }
      },
    ];

    const changeData = (value, key, row) => {
      const newData = [...data]
      if (_.isArray(key)) {
        const items = {}
        key.map((s, i) => {
          items[s] = value[i]
        })
        row = { ...row, ...items }
      } else {
        row[key] = value
      }

      // 处理编辑后的嵌套格式数据
      for (const data of newData) {
        const children = data.quotaModifyHistoryRespVoList
        // 通过quotaApplyForId和id确认唯一
        let index = children.findIndex(child => child.quotaApplyForId == row.quotaApplyForId && child.id == row.id)
        if (index > -1) {
          children[index] = row
          break
        }
      }
      setData(newData)
    }

    return <Table columns={columns} dataSource={dataSource} pagination={false} rowKey='id' />;
  };

  const columns = [
    // {
    //   title: '盘点周期', dataIndex: "description", render: (text, record) => {
    //     let red = record.red == 'Y'
    //     return <span className={red ? 'red' : ''}>{text}</span>
    //   }, width: 140
    // },
    {
      title: '客户编码', key: 'dealerCode', dataIndex: 'dealerCode', render: (text, record) => {
        let red = record.red == 'Y'
        return <span className={red ? 'red' : ''}>{text}</span>
      }, width: 140
    },
    { title: '客户名称', key: 'dealerName', dataIndex: 'dealerName', width: '140px' },
    { title: '销售组织', key: 'brandName', dataIndex: 'brandName', width: '140px' },
    { title: '客户类型', key: 'dealerType', dataIndex: 'dealerType', width: '140px', render: columnRenders.enum(EDealerType) },
    { title: '所属管理区域', key: 'belongAreaName', dataIndex: 'belongAreaName', width: '140px' },
    {
      title: '数据来源', key: 'sourceFrom', width: '140px', dataIndex: 'sourceFrom', render: (text) => (
        <span>{text == 'SYSTEM' ? '系统取数' : '手工导入'}</span>
      )
    },
    { title: '备注', key: 'remark', dataIndex: 'remark', minWidth: '140px' },
  ];

  const handelgetData = () => {
    let value = sessionStorage.getItem('checkedList')
    let alldata = value ? JSON.parse(value) : []
    setData(alldata)
  }
  const beforeNextpage = () => {
    // todo 提交审核接口
    // if (!sessionStorage.getItem('person')) {
    //   message.warning('请选择审批人')
    //   return
    // }
    let dataes = sessionStorage.getItem('person')
    let templates = sessionStorage.getItem('template')
    let resm = JSON.parse(dataes)
    let template = JSON.parse(templates)

    if (resm.length !== template.length) return message.warning('请选择节点审批人')
    // 弹出输入备注的弹窗
    toggleVisible(true)
  }
  const handleOk = () => {
    // 发起请求
    // if (!extraText) {
    //   message.warning('请输入备注消息')
    //   return 
    // }
    toggleLoading(true)
    nextPageContent()
  }
  const textChang = (e) => {
    const { value } = e.target;
    extraTextChange(value)
  }
  const handleCancel = () => {
    toggleVisible(false)
  }
  const nextPageContent = () => {
    let dataes = sessionStorage.getItem('person')
    let templates = sessionStorage.getItem('template')
    let resm = JSON.parse(dataes)
    let template = JSON.parse(templates)
    const { brandCode, brandName } = routeUtils.searchStringToObject(props.location.search, { brandCode: '', brandName: '' })

    // let list = template.filter(item => item.assignee.slice(0, 1) == '$')
    template.forEach((item, index) => {
      // TODO: 每项审核人支持多选，目前为单选，取第一条
      // 改为多选
      setFlowReqVos.push({
        name: item.assignee,
        userIds: resm[index] && resm[index].map((a: any) => a.id)
      })
    })
    let newvalue = data.map(item => item.quotaModifyHistoryRespVoList).flat(Infinity)
    const datavalue: any = {
      opinionDepiction: extraText,
      quotaModifyHistoryRespVoList: newvalue,
      workflowReqVos: setFlowReqVos,
      title: titleValue || props.match.params.brandName + props.match.params.times + '配额下达审批'
    }

    if (props.location.state?.brandCode) {
      datavalue['status'] = 'all';
      datavalue['brandCode'] = props.location.state.brandCode;
      datavalue['quotaModifyHistoryRespVoList'] = []
    } else {
      datavalue.brandCode = brandCode
      datavalue.brandName = brandName
    }

    http.post(apis.quotaTransmit, datavalue).then(resp => {
      sessionStorage.removeItem('person')
      sessionStorage.removeItem('template')
      sessionStorage.removeItem('checkedList')
      message.success('提交审核成功！')
      props.history.push('/quota/monthlyquota')
    })
  }
  const handelchaneginput = (e) => {
    setTitleValue(e.target.value)
  }

  console.log('titleValue', titleValue);
  return (
    <>
      <UdPage>
        <UdPageHeader title="配额下达提交审批" onBack={() => props.history.goBack()} />
        <div className="weaper-inp">
          <div>申请单标题:</div>
          <Input type="text"
            className="sty-input"
            size="large"
            max={20}
            value={titleValue}
            onChange={handelchaneginput}
          />
        </div>
        <UdTable
          loading={data.length < 1}
          className="components-table-demo-nested"
          columns={columns}
          expandedRowRender={expandedRowRender}
          dataSource={data}
          pagination={pagination}
          rowKey="id"
        />
        <div className="mar-top">
          <MultipleUser
            sort={data}
          />
        </div>
        <div className="buttomremove">
          <Button type="primary" onClick={beforeNextpage}>提交</Button>
        </div>
        {/* 备注弹窗 */}
        <Modal
          title="意见描述"
          visible={visible}
          onOk={handleOk}
          confirmLoading={confirmLoading}
          onCancel={handleCancel}
        >
          <TextArea rows={4} maxLength={300} placeholder="请输入意见描述(300字以内)" onChange={textChang} />
        </Modal>
      </UdPage>
    </>
  );
}

export default NestedTable
